<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="期限">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="期限开始"
          end-placeholder="期限结束"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="学号" prop="studentCode">
        <el-input
          v-model="queryParams.studentCode"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学员姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="studentStatus">
        <el-select v-model="queryParams.studentStatus" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.puyu_student_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="删除标识" prop="delFlag" v-if="showDelFlag()">
        <el-select v-model="queryParams.delFlag" placeholder="请选择删除标识" clearable>
          <el-option
            v-for="dict in dict.type.sys_del_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="训练类型" prop="trainingType">
        <el-select v-model="queryParams.trainingType" placeholder="请选择训练类型" clearable>
          <el-option
            v-for="dict in dict.type.puyu_training_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报名日期" prop="joinTime">
        <el-date-picker clearable
          v-model="queryParams.joinTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择报名日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="danger" icon="el-icon-search" size="mini" @click="handleQueryZero" v-hasPermi="['puyu:student:add']">课时用完</el-button>
        <el-button type="danger" icon="el-icon-search" size="mini" @click="handleQueryMonth" v-hasPermi="['puyu:student:add']">三个月内到期</el-button>
        <el-button type="danger" icon="el-icon-search" size="mini" @click="handleQueryFifteen" v-hasPermi="['puyu:student:add']">15天未上课</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['puyu:student:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['puyu:student:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['puyu:student:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['puyu:student:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学员ID" align="center" prop="studentId" />
     <!-- <el-table-column label="部门id" align="center" prop="deptId" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="家长用户ID" align="center" prop="parentUserId" /> -->
      <el-table-column label="学号" align="center" prop="studentCode" />
      <el-table-column label="学员姓名" align="center" prop="studentName" />
      <el-table-column label="手机号" width="120" align="center" prop="phone" />
      <el-table-column label="生日" align="center" prop="birthday" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="缴费" align="center" prop="money" />
      <el-table-column label="节数" align="center" prop="classNum" />
      <el-table-column label="剩余节数" align="center" prop="classBalance" />
      <el-table-column label="状态" align="center" prop="studentStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.puyu_student_status" :value="scope.row.studentStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="删除标识" align="center" prop="delFlag" v-if="showDelFlag()">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_del_flag" :value="scope.row.delFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="训练类型" align="center" prop="trainingType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.puyu_training_type" :value="scope.row.trainingType"/>
        </template>
      </el-table-column>
      <el-table-column label="报名日期" align="center" prop="joinTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.joinTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效日期" align="center" prop="expiredTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expiredTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['puyu:student:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleStudentLesson(scope.row)"
            v-hasPermi="['puyu:student:listLesson']"
          >消课记录</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleStudentStrengthTest(scope.row)"
            v-hasPermi="['puyu:student:listStrengthTest']"
          >体能指标</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['puyu:student:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学号" prop="studentCode">
          <el-input v-model="form.studentCode" placeholder="请输入学号" :disabled="isReadOnlyStudentCode" />
        </el-form-item>
        <el-form-item label="归属部门" prop="deptId" v-hasRole="['admin','manager']">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
        <el-form-item label="学员姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学员姓名" :disabled="isReadOnlyStudentName" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone" v-hasRole="['admin','manager']">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker clearable
            v-model="form.birthday"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择生日">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="缴费" prop="money" v-hasRole="['admin','manager']">
          <el-input v-model="form.money" placeholder="请输入缴费" />
        </el-form-item>
        <el-form-item label="节数" prop="classNum" v-hasRole="['admin','manager']">
          <el-input v-model="form.classNum" placeholder="请输入节数" />
        </el-form-item>
        <el-form-item label="状态" prop="studentStatus" v-hasRole="['admin','manager']">
          <el-radio-group v-model="form.studentStatus">
            <el-radio
              v-for="dict in dict.type.puyu_student_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除标识" prop="delFlag" v-if="showDelFlagItem()">
          <el-select v-model="form.delFlag" placeholder="请选择删除标识">
            <el-option
              v-for="dict in dict.type.sys_del_flag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="训练类型" prop="trainingType" v-hasRole="['admin','manager']">
          <el-select v-model="form.trainingType" placeholder="请选择训练类型">
            <el-option
              v-for="dict in dict.type.puyu_training_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="期限类型" prop="expiredType" v-hasRole="['admin','manager']">
          <el-select v-model="form.expiredType" placeholder="请选择期限类型">
            <el-option
              v-for="dict in dict.type.puyu_student_expired_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报名日期" prop="joinTime" v-hasRole="['admin','manager']">
          <el-date-picker clearable
            v-model="form.joinTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择报名日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark" v-hasRole="['admin','manager']">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "../../../utils/ruoyi";
import { listStudent, getStudent, delStudent, addStudent, updateStudent, listStudentUser, listStudentParentUser, getStudentCode, listStudentNames } from "@/api/puyu/student";
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Student",
  dicts: ['puyu_training_type', 'puyu_student_status', 'sys_del_flag', 'puyu_student_expired_type'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日期范围
      dateRange: [],
      // 学员表格数据
      studentList: [],
      // 学员用户数据
      studentUserList: undefined,
      // 学员家长用户数据
      studentParentUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门树选项
      deptOptions: undefined,
      // 学员用户
      isReadOnlyStudentUserId: false,
      // 学员姓名
      isReadOnlyStudentName: false,
      // 学员编号
      isReadOnlyStudentCode: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        userId: null,
        parentUserId: null,
        studentCode: null,
        studentName: null,
        phone: null,
        birthday: null,
        money: null,
        classNum: null,
        studentStatus: null,
        trainingType: null,
        joinTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        studentName: [
          { required: true, message: "学员姓名不能为空", trigger: "blur" },
          { validator: this.validateUsername, trigger: 'change' }
        ],
        phone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        expiredType: [
          { required: true, message: "期限类型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getStudentUserList();
    this.getStudentParentUserList();
  },
  methods: {
    validateUsername(rule, value, callback) {
      let data = {'studentName': value};
      listStudentNames(data).then(response => {
        if (response.data.length) {
          if (this.form.studentId == null || this.form.studentId != response.data[0].studentId) {
          	callback(new Error('有同名学员！'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      });
    },
    /** 查询学员列表 */
    getList() {
      this.loading = true;
      listStudent(this.addDateRange(this.queryParams, this.dateRange, 'ExpiredTime')).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询学员用户列表 */
    getStudentUserList() {
      listStudentUser().then(response => {
        this.studentUserList = response.data;
      });
    },
    /** 查询学员用户列表 */
    getStudentParentUserList() {
      listStudentParentUser().then(response => {
        this.studentParentUserList = response.data;
      });
    },
    /** 下拉选择学员用户 */
    handleStudentUserChange(studentUser) {
      this.form.deptId = studentUser.deptId;
      this.form.studentName = studentUser.nickName;
      this.form.phone = studentUser.phoneNumber;
    },
    selectStudentCode() {
      getStudentCode().then(response => {
        this.form.studentCode = response.data.studentCode;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        studentId: null,
        deptId: null,
        userId: null,
        parentUserId: null,
        studentCode: null,
        studentName: null,
        phone: null,
        birthday: null,
        money: null,
        classNum: null,
        studentStatus: null,
        trainingType: null,
        joinTime: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.params['beginFifteenDays'] = '';
      this.getList();
    },
    /** 课时用完按钮操作 */
    handleQueryZero() {
      this.queryParams.classBalance = 0;
      this.queryParams.pageNum = 1;
      this.queryParams.params['beginFifteenDays'] = '';
      this.getList();
    },
    /** 三个月内到期学员查询 */
    handleQueryMonth() {
      let begin = new Date();
      let end = this.addMonths(begin, 3);
      this.dateRange = [parseTime(begin, '{y}-{m}-{d}'), parseTime(end, '{y}-{m}-{d}')];
      this.queryParams.pageNum = 1;
      this.queryParams.params['beginFifteenDays'] = '';
      this.getList();
    },
    /** 15天未上课学员查询 */
    handleQueryFifteen() {
      let end = new Date();
      let begin = this.addDays(end, -15);
      let dateRange = [parseTime(begin, '{y}-{m}-{d}'), parseTime(end, '{y}-{m}-{d}')];
      this.queryParams.pageNum = 1;

      this.loading = true;
      listStudent(this.addDateRange(this.queryParams, dateRange, 'FifteenDays')).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.classBalance = null;
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.studentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.selectStudentCode();
      // 默认1年处理
      this.form.expiredType = 3;
      this.open = true;
      this.title = "添加学员";
      this.isReadOnlyStudentCode = false;
      this.isReadOnlyStudentName = false;
      this.isReadOnlyStudentUserId = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const studentId = row.studentId || this.ids
      getStudent(studentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学员";
        this.isReadOnlyStudentCode = true;
        this.isReadOnlyStudentName = false;
        this.isReadOnlyStudentUserId = false;
      });
    },
    // 消课记录
    handleStudentLesson(row) {
      const studentId = row.studentId;
      this.$router.push("/puyu/student-lesson/lesson/" + studentId);
    },
    handleStudentStrengthTest(row) {
      const studentId = row.studentId;
      this.$router.push("/puyu/student-strength/strength/" + studentId);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.studentId != null) {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const studentIds = row.studentId || this.ids;
      this.$modal.confirm('是否确认删除学员编号为"' + studentIds + '"的数据项？').then(function() {
        return delStudent(studentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('puyu/student/export', {
        ...this.queryParams
      }, `student_${new Date().getTime()}.xlsx`)
    },
    /** 日期月份添加处理 */
    addMonths(date, months) {
      const newDate = new Date(date.getTime());
      newDate.setMonth(newDate.getMonth() + months);
      return newDate;
    },
    /** 日期日份添加处理 */
    addDays(date, days) {
      const newDate = new Date(date.getTime());
      newDate.setDate(newDate.getDate() + days);
      return newDate;
    },
    showDelFlag() {
      return this.$auth.hasRoleOr(["admin", "manager"]);
    },
    showDelFlagItem() {
      return this.$auth.hasRoleOr(["admin", "manager"]) && this.form.studentId != null;
    },
  }
};
</script>
<style lang="scss" scoped>
  .same-name {
  	margin-top: 15px;
  	color: red;
  }
</style>
